package com.gq.utils;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.support.v4.app.FragmentActivity;

import com.gq.thandongdatviet.NoNetworkActivity;


public class NetworkState {
	
	private static final String TAG = NetworkState.class.getSimpleName();
	private Context context;
	
	public NetworkState(Context context) {
		this.context = context;
	}
	
	public boolean hasConnection() {
		ConnectivityManager conmgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeInfo = conmgr.getActiveNetworkInfo();
		if (activeInfo != null) {
			if (activeInfo.getState() == State.CONNECTED) {
				return true;
//				try {
//					URL uri = new URL("http://a.p.mana.vn");
//					HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
//					int response = conn.getResponseCode();
//					if (response == HttpURLConnection.HTTP_OK) {
//						return true;
//					}
//				} catch (MalformedURLException e) {
//					e.printStackTrace();
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
			}
		}
		return false;
	}
	
	public void check() {
		ConnectivityManager conmgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeInfo = conmgr.getActiveNetworkInfo();
		if (activeInfo != null) {
			if (activeInfo.getState() == State.CONNECTED) {
				return;
			}
		}
		((Activity) context).finish();
		Intent intent = new Intent(context, NoNetworkActivity.class);
		intent.putExtra("INTENT", ((Activity) context).getIntent());
		context.startActivity(intent);
	}
}
